import { type User } from "@/types";
import Cookies from "js-cookie";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

export const cookieKey = "user-token";
interface UserState {
  user: User | null;
  login: (token: string) => void;
  setUser: (user: User) => void;
  logout: () => void;
  getToken: () => string | undefined;
}
export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      user: null,
      login: (token: string) => {
        Cookies.set(cookieKey, token, { expires: 30 });
      },
      setUser: (user: User) => set(() => ({ user })),
      logout: () => {
        set(() => ({ user: null }));
        Cookies.remove(cookieKey);
      },
      getToken: () => Cookies.get(cookieKey),
    }),
    {
      name: "user",
      storage: createJSONStorage(() => localStorage),
    }
  )
);
